<template>
	<div>
		<!--        用户-->
		<el-row style="margin-bottom: 50px">
			<el-col :span="24" >
				<el-card shadow="never" style="max-width: 100%">
					<template #header>
						<div class="card-header">
							<span>上传商品用户信息</span>
						</div>
					</template>
					<el-descriptions>
						<el-descriptions-item label="用户昵称">{{ state.userInfo.nickName }}</el-descriptions-item>
						<el-descriptions-item label="用户手机号">{{ state.userInfo.cellPhone !== "" ? state.userInfo.cellPhone:"无" }}</el-descriptions-item>
						<el-descriptions-item label="用户上传时间">{{ state.info.createTime }}</el-descriptions-item>
<!--						<el-descriptions-item label="是否授权商">-->
<!--							<el-tag size="small">{{ state.userInfo.isAccredit === 0 ? '不是' : '是' }}</el-tag>-->
<!--						</el-descriptions-item>-->
<!--						<el-descriptions-item label="角色类型">-->
<!--							<el-tag size="small">{{ state.userInfo.roleType === 0 ? '自营' : '普通用户' }}</el-tag>-->
<!--						</el-descriptions-item>-->
					</el-descriptions>
					<!--          <template #footer>Footer content</template>-->
				</el-card>
			</el-col>
		</el-row>
		<el-form ref="ruleFormRef" :model="state.from" :rules="state.rules">
			<!--        商品-->
			<el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="商品编号" style="width: 400px" prop="productId">
							<el-input disabled v-model="state.from.productId"/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="商品名称" style="width: 400px" prop="productName">
							<el-input  v-model="state.from.productName" placeholder="请输入商品名称"/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-col :span="24">
					<el-form-item label="项目图片" prop="productImg">
						<el-upload
							class="avatar-uploader"
							:action="uploadUrl"
							:show-file-list="false"
							accept=".jpg,.png"
							:on-success="productImgHandleSuccess">
							<img style="width: 180px;height: 150px" v-if="state.from.productImg" :src="state.from.productImg"/>
							<el-icon v-else class="avatar-uploader-icon">
								<Plus/>
							</el-icon>
						</el-upload>
					</el-form-item>
					<el-row :gutter="20">
						<el-col :span="6">
							<el-form-item label="基础价格" style="width: 300px" prop="priceCurrentPrice">
								<el-input-number v-model="state.from.priceCurrentPrice" :min="0.01" :max="10000"/>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="部署价格" style="width: 300px" prop="priceDeploy">
								<el-input-number v-model="state.from.priceDeploy" :min="0.01" :max="10000"/>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="全套价格" style="width: 300px" prop="priceGuide">
								<el-input-number v-model="state.from.priceGuide" :min="0.01" :max="10000"/>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="推荐比例（%）" style="width: 300px" prop="priceAccreditRate">
								<el-input-number v-model="state.from.priceAccreditRate" :min="0.01" :max="1"/>
							</el-form-item>
						</el-col>
					</el-row>

					<el-form-item label="商品标签" style="width: 665px" prop="productTag">
						<el-input :rows="3" type="textarea" v-model="state.from.productTag"/>
					</el-form-item>

					<el-form-item label="商品类别" style="width: 300px" prop="categoryId">

						<el-cascader
							placeholder="请选择分类"
							v-model="state.from.categoryId"
							:options="state.cateList"
							:props="props"
							@change="handleBaseValue"
						/>
					</el-form-item>
					<el-form-item label="商品简介" style="width: 665px" prop="productIntro">
						<el-input :rows="6" type="textarea" v-model="state.from.productIntro"
											placeholder="一段简短的话表示商品的重点信息"/>
					</el-form-item>
					<el-form-item label="商品详情" style="width: 90%;height: 500px" prop="productDesc">
						<MdEditor
							@onUploadImg="onUploadImg"
							v-model="state.from.productDesc"/>
					</el-form-item>

				</el-col>
			</el-row>
			<!--文件-->
			<el-row>
				<el-col :span="24">
					<el-row style="margin-bottom: 50px">
						<el-form-item label="B站链接引入" prop="bzImps" style="width: 90%;height: 200px">
							<el-descriptions direction="vertical" :column="4" border>
								<el-descriptions-item label="内容区" :span="2">
									<div style="width: 300px;height: 100%">
										<el-input  :rows="8" type="textarea" v-model="state.from.bzImps"/>
									</div>
								</el-descriptions-item>
								<el-descriptions-item label="上传内容展示区域">
									<div style="width:300px;height:  100%" v-html="state.from.bzImps"></div>
								</el-descriptions-item>
								<el-descriptions-item label="备注">
                  <span style="color: #FF0000">
                    {{state.from.bzImps === '' ? "用户没有引入B站内容" : "用户有引入B站内容" }}
                  </span>
								</el-descriptions-item>
							</el-descriptions>
						</el-form-item>
					</el-row>
					<!--          视频上传-->
					<el-row style="margin-bottom: 20px">
						<el-form-item label="本地视频" style="width: 500px">
							<el-descriptions direction="vertical" :column="4" border>
								<el-descriptions-item label="视频操作区" :span="2">
									<div style="width: 300px;height: 100%">
<!--										<el-button type="success" plain>点击{{ state.from.videoFile.length === 0 ? '添加' : '更换' }}视频-->
<!--											<el-icon class="el-icon&#45;&#45;right"><Upload/></el-icon>-->
<!--										</el-button>-->
										<el-upload :action="VideoUploadUrl" multiple :limit="1" :on-success="videoHandleSuccess" accept=".mp4">
										</el-upload>
									</div>
								</el-descriptions-item>
								<el-descriptions-item label="视频内容区">

									<div style="width:300px;height:  100%">
                    <span
											style="color: #FF0000"
											v-if="state.from.videoFile === ''"> 用户没有上传此视频</span>
										<video
											v-else
											v-if="state.from.videoFile !== ''"
											controls
											style="width: 300px;height: 100%"
											:src="state.from.videoFile"
											type="audio/mp4">
										</video>
									</div>
								</el-descriptions-item>
							</el-descriptions>
						</el-form-item>
					</el-row>
					<!--          文件包-->
					<el-row style="margin-bottom: 20px">
						<el-form-item label="文件包" style="width: 500px" prop="packFiles">
							<el-descriptions direction="vertical" :column="4" border>
								<el-descriptions-item label="操作区" :span="2">
									<div style="width: 300px;height: 100%">
										<div style="width: 100%;height: 150%;margin-bottom: 10px">
											<el-upload
												:action="fileUploadUrl" multiple :limit="1" :on-success="codeFileHandleSuccess" accept=".zip">
												<el-button type="primary" :icon="FolderOpened">
													{{ state.from.packFiles === null ? '添加' : '更换' }}文件包
												</el-button>
											</el-upload>
										</div>
										<el-button type="primary" :icon="Download" v-if="state.from.packFiles!== null" @click="download(state.from.packFiles)">下载文件包</el-button>
									</div>
								</el-descriptions-item>
								<el-descriptions-item label="上传内容">
<!--									<div style="width:300px;height:  100%" v-html="state.info.bzImps"></div>-->
								</el-descriptions-item>
							</el-descriptions>
						</el-form-item>
					</el-row>
				</el-col>
			</el-row>
			<!--审核-->
			<el-row>
				<el-col :span="24">
					<el-form-item label="审核状态" prop="auditStatus" style="width: 500px">
						<el-radio-group v-model="state.from.auditStatus">
							<el-radio value=1 >通过</el-radio>
							<el-radio value= 2 >拒绝</el-radio>
						</el-radio-group>
						<el-input
							v-if="state.from.auditStatus === '2'" :rows="6" type="textarea" v-model="state.from.auditError"/>
					</el-form-item>
					<el-form-item label="是否上架">
						<el-radio-group v-model="state.from.productIsPutaway">
							<el-radio value= 1 >上 架 </el-radio>
							<el-radio value= 0 >下 架 </el-radio>
						</el-radio-group>
					</el-form-item>
					<!--			佣金-->
					<el-form-item label="最终佣金">
						<el-button v-if="state.openCommission == true" @click="openCommission(false)">开启分佣</el-button>
						<el-button v-else @click="openCommission(true)">关闭分佣</el-button>
						<el-input-number :disabled="state.openCommission" v-model="state.from.commission" :min="0.00" :max="500"  :precision="2"/>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<el-dialog
			v-model="state.timeDialogVisible"
			title="时间线添加"
			width="500"
			draggable
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-row :gutter="20">
				<el-col :span="8">
					<el-timeline style="max-width: 600px">
						<el-timeline-item
							v-for="(activity, index) in state.version"
							:key="index"
							:timestamp="activity.time"
						>
							{{ activity.name }}
						</el-timeline-item>
					</el-timeline>
				</el-col>
				<el-col :span="16">
					<el-form
						label-position="top"
						:model="state.timeFrom"
						label-width="auto"
						style="max-width: 600px">
						<el-form-item label="版本名称">
							<el-input maxlength="300" :rows="6" show-word-limit
												type="textarea" v-model="state.timeFrom.name"/>
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="timeFrom">提交</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import type {FormInstance} from 'element-plus';
import type {UploadProps} from 'element-plus';
import {Plus, Upload, Download, FolderOpened} from '@element-plus/icons-vue';
import {useRoute, useRouter} from 'vue-router'
const {params} = useRoute()
const router = useRouter()
import axios from "axios";
import {signGengw} from "~/composables/md5";
import {ProductService} from "~/api/product";
const ruleFormRef = ref<FormInstance>();
// 计算属性返回完整的上传 URL
const uploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/api/file/upload?type=0`);
const VideoUploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/api/file/upload?type=1`);
const fileUploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/api/file/upload?type=2`);
// 获取路径参数
const productId: any = params.id;
const state = reactive(<any>{
	openCommission:true,
	//版本时间提交
	timeFrom: {
		productId: productId,
		name: ""
	},
	//版本弹出框
	timeDialogVisible: false,
	imgPath: import.meta.env.VITE_IMG_PATH,
	resImgList: [],
	context: '', // 输入的数据
	dialogVisibleImg: false,
	cateList: [],
	itemInfo: {},
	userInfo: {},
	info: {},
	rules: {
		productId: [
			{required: true, message: '商品编号不能为空', trigger: 'blur'}
		],
		productName: [
			{required: true, message: '商品名称不能为空', trigger: 'blur'},
			{min: 3, max: 50, message: '长度在 2 到 25 个字符', trigger: 'blur'}
		],
		priceCurrentPrice: [
			{required: true, message: '基础价格不能为空', trigger: 'blur'},
			{
				pattern: /^\d{1,10}(\.\d{1,2})?$/,
				message: '请输入有效的金额（整数部分最多10位，小数部分最多2位）',
				trigger: 'blur'
			}
		],
		priceDeploy: [
			{required: true, message: '部署价格不能为空', trigger: 'blur'},
			{
				pattern: /^\d{1,10}(\.\d{1,2})?$/,
				message: '请输入有效的金额（整数部分最多10位，小数部分最多2位）',
				trigger: 'blur'
			}
		],
		priceGuide: [
			{required: true, message: '全套价格不能为空', trigger: 'blur'},
			{
				pattern: /^\d{1,10}(\.\d{1,2})?$/,
				message: '请输入有效的金额（整数部分最多10位，小数部分最多2位）',
				trigger: 'blur'
			}
		],
		priceAccreditRate: [
			{required: true, message: '百分比不能为空', trigger: 'blur'},
		],

		auditStatus: [
			{required: true, message: '审核状态不能为空', trigger: 'blur'}
		],
		categoryId: [
			{required: true, message: '审核类别不能为空', trigger: 'blur'}
		],
		productDesc: [
			{required: true, message: '审核详情不能为空', trigger: 'blur'}
		],
		packFiles: [
			{required: true, message: '文件包不能为空', trigger: 'blur'}
		],
		productIntro: [
			{required: true, message: '商品介绍不能为空', trigger: 'blur'}
		],
		productImg: [
			{required: true, message: '商品图片不能为空', trigger: 'blur'}
		],

	},
	version: [],
	from:{
		commission:0.00
	}
});
const props = {
	value: 'categoryId',
	label: 'categoryName',
	children: 'getCategoryVo'
};

function init() {
	ProductService.getProductInfo({"productId": productId}).then(res =>{
		console.log(res.data)
		state.userInfo = res.data.getUserVo
		state.info = res.data
		//转换字符串

		//商品详情类 start
		state.from.productId = res.data.productId;
		state.from.productName = res.data.productName;
		state.from.productImg = res.data.productImg;
		state.from.productTag = res.data.productTag;
		state.from.productDesc = res.data.productDesc;
		state.from.productIntro = res.data.productIntro;
		//商品详情类 end

		//价格  start
		state.from.priceCurrentPrice = parseFloat(res.data.priceCurrentPrice) ;
		state.from.priceDeploy = parseFloat(res.data.priceDeploy) ;
		state.from.priceGuide = parseFloat(res.data.priceGuide) ;
		state.from.priceAccreditRate = parseFloat(res.data.priceAccreditRate) ;
		//价格 end
		//审核B站内容
		state.from.bzImps =  res.data.bzImps.length === 0 ? '' : res.data.bzImps[0].fileUrl
		state.from.videoFile = res.data.videoFiles.length === 0 ? '' : res.data.videoFiles[0].fileUrl
		state.from.packFiles = res.data.packFiles.length === 0 ? '' : res.data.packFiles[0].fileUrl

		state.from.categoryId = res.data.categoryId.toString();
		state.from.productIsPutaway = res.data.productIsPutaway.toString();
		state.from.auditStatus = res.data.auditStatus.toString();
		state.from.providerId = res.data.providerId;
	})


	http.post('/api/category/categoryList', signGengw({})).then((res: any) => {
		state.cateList = res.data;
		if (state.cateList.length > 0) {
			state.cateList.forEach((item: any) => {
				clickCategory(item);
			});
		}
	});
}

/**
 * 开启分佣
 * @param val
 */
function openCommission(status:boolean) {
	if (status) {
		state.from.commission = 0.00
	}
	state.openCommission = status
}

function handleBaseValue(val) {
	state.from.categoryId = val[val.length - 1];
}

//时间线提交
function timeFrom() {
	if (state.timeFrom.name == '') {
		toast.error("版本名称不能为空")
		return
	}
	http.post("/api/admin/productVersion/save", state.timeFrom).then(() => {
		toast.success('添加成功');
		state.timeDialogVisible = false
		//回到商品页
		router.push("/product")
	})
}


/**
 * markdown上传文件
 * @param files
 * @param callback
 */
function onUploadImg(files: any, callback: any) {
	const uploadPromises = [];
	for (let i = 0; i < files.length; i++) {
		const formdata = new FormData();
		formdata.append('file', files[i]);
		formdata.append('type', 7);
		const uploadPromise = axios.post("https://xunyingcloud.cn/xcp/api/file/upload", formdata, {
			headers: {'Content-Type': 'multipart/form-data'}
		}).then(res => res.data.data.url);
		uploadPromises.push(uploadPromise);
	}
	Promise.all(uploadPromises)
		.then(resImgList => {
			console.log(resImgList);
			callback(resImgList);
		})
		.catch(error => {
			console.error('Error uploading images:', error);
			callback([]);
		});
}


/**
 * 代码包文件下载
 * @param data
 */
function download(data: any) {
	if (data !== null) {
		let link = document.createElement('a');
		link.style.display = 'none';
		link.href = data;
		link.setAttribute('download', '导出代码压缩包');
		document.body.appendChild(link);
		link.click();
	} else {
		toast.warning('没有附件，无法下载');
	}
}

function clickCategory(item: any) {
	http.post('/api/category/clickCategory', signGengw({firstSysId: item.categoryId})).then((res: any) => {
		if (res.code == 200) {
			item.getCategoryVo = res.data;
		}
	});
}

//商品文件上传成功时的钩子
const productImgHandleSuccess: UploadProps['onSuccess'] = (response) => {
	//把地址截取获取图片位置
	state.from.productImg = response.data.url;
};
//视频上传成功时的钩子 start
const videoHandleSuccess: UploadProps['onSuccess'] = (response) => {
	//显示视频
	state.from.videoFile = response.data.url;
};
//代码更换上传钩子
const codeFileHandleSuccess: UploadProps['onSuccess'] = (response) => {
	//显示视频
	state.from.packFiles = response.data.url;
};
//数据提交
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if (state.from.auditStatus === '2' && state.from.auditError === '') {
		toast.error('审核拒绝: 拒绝内容不能为空!');
	}
	if (state.from.videoFile === null && state.from.bzImps === null) {
		toast.error('B站引入和本地视频不能都为空');
		return;
	}
	if (state.from.packFiles === null) {
		toast.error('用户没有上传文件包，不允许上传！');
		return;
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log(state.from)
			http.post("/api/admin/product/verifyProductAdmin", state.from).then(() => {
				toast.success('修改成功');
				state.timeDialogVisible = true
			})
		}else {
			console.log('error submit!', fields)
		}
	});
};


init();
</script>


<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}


</style>
